#include <iostream>
#include <memory>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#include "HttpServer.hpp"
#include "Usage.hpp"
#include "Util.hpp"

#define ROOT "./wwwroot" // web根目录
// 如果客户端只请求一个/，则返回默认路径
#define HOMEPAGE "index.html"

void HandlerHttpRequest(int sockfd)
{
    // 读取请求
    char buffer[10240];
    ssize_t s = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if (s > 0)
    {
        buffer[s] = 0;
        std::cout << buffer << "--------------------\n"<< std::endl;
    }

    std::vector<std::string> vline;
    Util::cutString(buffer, "\r\n", &vline);

    std::vector<std::string> vblock;
    Util::cutString(vline[0], " ", &vblock);

    std::string file = vblock[1];
    std::string tartget = ROOT;
    if (file == "/")
        file = "/index.html";
    tartget += file;
    std::cout << tartget << std::endl;

    std::string content;
    // int fd=open(tartget.c_str(),O_RDONLY);
    std::ifstream in(tartget);
    if (in.is_open())
    {
        std::string line;
        while (std::getline(in, line))
        {
            content += line;
        }
        in.close();
    }
    std::string httpresponse;
    if (content.empty())
    {
        httpresponse = "Http/1.1 302 Found \r\n";
        // 重定向到一个网址,若要访问的页面不存在，则会重定向访问这个页面/网址
        httpresponse += "Location: https://www.qq.com/\r\n";
    }
    else
    {
        httpresponse = "Http/1.1 200 ok\r\n";
        httpresponse+=("Content-Type: text/html\r\n");
        // httpresponse+=("Content-Type: text/plain\r\n");  //纯文本显示
        // 输出正文内容多少字节
        httpresponse+=("Content-Length: "+std::to_string(content.size())+"\r\n");
        httpresponse+="Set-Cookie: 这是一个cookie\r\n";
    }
    httpresponse += "\r\n";
    httpresponse += content;
    // std::cout<<"####start#################"<<std::endl;
    // for (auto &iter : vblock)
    // {
    //     std::cout<<"---" << iter << "\n"<< std::endl;
    // }
    // std::cout<<"####end#################"<<std::endl;

    // http的响应
    // httpresponse += "<html><h3>hello world</h3><html>";
    send(sockfd, httpresponse.c_str(), httpresponse.size(), 0); // 发送给客户端
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]), HandlerHttpRequest));
    httpserver->Start();

    return 0;
}